/**
 * @Name:  WaterFall
 * @Author:
 * @Desc:  瀑布流展示
 * @Date: 2021-01-05 09:28:20
 */
import React, { Component } from "react";
import $ from "jquery";
import { Title } from "@/component";
import { Empty, Spin } from "antd";
import { getNewsList } from "@/api/test";
import { averageListArr } from "@/utils";

import styles from "./styles.module.less";

const defaultWidth = 168;
class WaterFall extends Component {
  state = {
    jokeList: [],
    jokeListOriginal: [],
    listNum: 10,
    page: 1,
    pageSize: 20,
    end: false,
    loadingText: ""
  };
  async componentDidMount() {
    // window.addEventListener("resize", this.resize);
    window.addEventListener("scroll", this.scroll);

    this.init();
  }
  componentWillUnmount() {
    // window.removeEventListener("resize", this.resize);
    window.removeEventListener("scroll", this.scroll);
  }
  /**
   * @name scroll
   * @description 滚动事件
   */
  scroll = () => {
    const { page, loading } = this.state;
    //窗口高度
    let windowHeight = document.documentElement.clientHeight;
    //滚动条滑动距离
    let scrollHeight = document.documentElement.scrollTop;
    //页面文档总体高度
    let documentHeight = document.documentElement.scrollHeight;
    if (documentHeight - windowHeight === scrollHeight && !loading) {
      if (page > 9) {
        this.setState({ end: true, loadingText: "到底了..." });
      } else {
        this.setState(
          {
            page: page + 1,
            loading: true
          },
          () => {
            this.init();
          }
        );
      }
    }
  };
  /**
   * @name resize
   * @description 页面缩放变化
   */
  resize = () => {
    const { jokeListOriginal } = this.state;
    const clientWidth = $("#joke_out_body").width();

    const num = Math.floor(clientWidth / (defaultWidth + 20));
    this.setState({ listNum: num });
    this.assembleData(jokeListOriginal, num);
  };
  /**
   * @name init
   * @description 初始化请求
   */
  init = async () => {
    let typeList = ["shehui", "guonei", "guoji", "yule", "tiyu", "junshi", "keji", "caijing", "shishang"];
    const { jokeListOriginal = [], page } = this.state;

    const clientWidth = $("#joke_out_body").width();

    const num = Math.floor(clientWidth / (defaultWidth + 20));
    //30条数据一页,向上取整
    const { type, data } = await getNewsList(typeList[page - 1]);
    let baseData = [];
    let end = false;
    let loadingText = "";
    if (type) {
      baseData = data.map((v, index) => {
        return {
          ...v,
          tag: page + "-" + index
        };
      });
    } else {
      end = true;
      loadingText = "加载失败...";
      return;
    }

    let originData = jokeListOriginal.concat([baseData]);
    this.setState({ jokeListOriginal: originData, loadingText, listNum: num, end }, () => {
      this.assembleData(originData, num);
    });
    // setTimeout(() => {
    //   this.setState({ jokeList: [{ code: "121" }] });
    // }, 3000);
  };
  /**
   * @name assembleData
   * @param {Array} data 二维数组的数据[[old],[new]]
   * @param {Number} 列数
   * @description 组装数据
   */
  assembleData = (data = [], num) => {
    let arr = [];
    if (data.length > 0) {
      arr = data.reduce((pre, cur, index) => {
        //子级数组-分块组装
        let baseData = averageListArr(cur, num, this.state.page);
        if (index >= 1) {
          pre = this.aveDis(pre, baseData);
          return pre;
        } else {
          //把当前子级数组分列
          pre = baseData;
          return pre;
        }
      }, []);
    }
    this.setState({ jokeList: arr, loading: false });
  };
  /**
   * @name aveDis
   * @param {Array} oldArr 旧数据数据
   * @param {Array} newArr 新数据分块后
   * @description 将新数据分块 ，插入对应旧数据块
   */
  aveDis = (oldArr, newArr) => {
    let arr = [];
    for (let i = 0; i < oldArr.length; i++) {
      let concatArr = oldArr[i].concat(newArr[i]);
      arr.push(concatArr);
    }
    return arr;
  };
  render() {
    const { loading, end, loadingText } = this.state;
    // const sessData = window.sessionStorage.getItem("waterfall");
    // const tagNum = sessData ? Number(JSON.parse(sessData)) : 0;
    // console.log("wate-index=======", tagNum);
    // let jokeList = tagNum > 0 ? this.state.jokeList : [{ code: 0 }];
    let jokeList = [{ code: 0 }];
    return (
      <div>
        <div className={styles.block}>
          <div>
            <Title text={"瀑布流展示"} />
          </div>
          <div id="joke_out_body">
            {jokeList instanceof Array && jokeList.length > 0 ? (
              <div className={styles.joke_out_body}>
                {jokeList.map((item, index) => (
                  <div key={"joke" + index} className={styles.joke_body} style={{ width: defaultWidth }}>
                    {item.map((v) => (
                      <div key={v.tag} className={styles.div_li}>
                        <img src={v.thumbnail_pic_s} style={{ width: "100%", height: "auto" }} alt="" />
                        <a href={v.url} className={styles.url_title}>
                          {v.title}
                        </a>
                        <div className={styles.tag}>来源：{v.author_name}</div>
                        <div className={styles.tag}>时间：{v.date}</div>
                        <div className={styles.tag_time}>标记：{v.tag}</div>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            ) : (
              <Empty style={{ margin: "0 auto" }} />
            )}
            {loading && jokeList instanceof Array && jokeList.length > 0 && (
              <Spin spinning={loading}>
                <div className={styles.loading_body}>{loadingText}</div>
              </Spin>
            )}
            {end && <div className={styles.loading_body}>{loadingText}</div>}
          </div>
        </div>
      </div>
    );
  }
}
export default WaterFall;
